# encoding: utf-8

class Utility::Page
  include Mongoid::Document
  include Mongoid::CriteriaExt
  include Utility::Retval
  field :page_token,  :type => String
  field :tweets,      :type => Array, :default => []
  field :is_finish,   :type => String
  field :search_type, :type => String
  field :total_num,   :type => Integer
  field :result_page, :type => Integer, :default => 0
  field :selected,    :type => Hash, :default => {}

  attr_accessor :has_result,
                :task,
                :current_page,
                :page_cache

  # field :number, :type => Integer
  # field :for_weibo, :type => Integer

  # belongs_to :task

  def self.make_page(task)
    page = Utility::Page.new(
    :page_token   => "#{task._id}_#{task.search_type.downcase}_p#{task.current_page}",
    :current_page => task.current_page,
    :task         => task,
    :search_type  => task.search_type
    )
    page.page_cache = Utility::Page.find_or_create_by(:page_token => "#{task._id}_#{task.search_type.downcase}_cache")
    page.tweets = page.page_cache.tweets
    page
  end

  def validate_weibo(user)
    return false unless user
    return true if user["id"].nil? || user["id"].empty?
    wuser = Statistics::SnsUser.where(:uid => user["id"]).first
    if wuser && (Time.now - wuser.recent_sent < gaps)
      logger.info ">查询状态: 用户#{user["screen_name"]}被防打扰机制屏蔽"
      return false
    # else
    #   Statistics::WeiboUser.create(:uid => user["id"])
    #   return true
    end
    return true
  end

  def add_weibo(weibo)
    if validate_weibo(weibo[:uid])
      self.tweets << weibo_builder(weibo)
      # self.weibo_count += 1
    end
  end

  def increase_rpage(rp)
    self.result_page = rp
    self.save
  end

  def make_cache
    if tweets.length > Task::PER_PAGE
      page_cache.tweets       =  self.tweets[Task::PER_PAGE, self.tweets.length - Task::PER_PAGE]
    end

    error ||= ""
    if error.empty?
      self.tweets       = self.tweets[0, Task::PER_PAGE]
    end
    page_cache.is_finish      =  self.is_finish
    page_cache.total_num      =  self.total_num
    page_cache.result_page    =  self.result_page
    page_cache.save

    self.current_page     = task.current_page
    self.save
    self
  end

  def weibo_builder(options = {})
    {
    "created_at"              => options[:created_at],
    "id"                      => options[:mid],
    "text"                    => options[:text],
    "source"                  => '<a href="http =>//weibo.com" rel="nofollow">新浪微博</a>',
    "favorited"               => false,
    "truncated"               => false,
    "in_reply_to_status_id"   => "",
    "in_reply_to_user_id"     => "",
    "in_reply_to_screen_name" => "",
    "thumbnail_pic"           => options[:thumbnail_pic],
    "bmiddle_pic"             => options[:bmiddle_pic],
    "original_pic"            => options[:large_pic],
    "geo"                     => nil,
    "mid"                     => options[:mid],
    "reposts_count"           => nil,
    "comments_count"          => nil,
    "annotations"             => [],
    "user"                    => {
      "id"                      => options[:uid],
      "screen_name"             => options[:screen_name],
      "name"                    => options[:screen_name],
      "province"                => "",
      "city"                    => "",
      "location"                => "",
      "description"             => "",
      "url"                     => "",
      "profile_image_url"       => options[:profile_image_url],
      "domain"                  => "",
      "gender"                  => "",
      "followers_count"         => nil,
      "friends_count"           => nil,
      "statuses_count"          => nil,
      "favourites_count"        => 0,
      "created_at"              => "",
      "following"               => false,
      "allow_all_act_msg"       => false,
      "remark"                  => "",
      "geo_enabled"             => true,
      "verified"                => false,
      "allow_all_comment"       => true,
      "avatar_large"            => "",
      "verified_reason"         => "",
      "follow_me"               => false,
      "online_status"           => 0,
      "bi_followers_count"      => nil
      }
    }
  end

  def tencent_builder(tweets)
    ts = tweets.map do |tweet|
      {
        "created_at"              => Time.at(tweet["storetime"].to_i),
        "id"                      => tweet["id"],
        "text"                    => tweet["text"].html_safe,
        "source"                  => '<a href="http =>http://t.qq.com" rel="nofollow">腾讯微博</a>',
        "favorited"               => false,
        "truncated"               => false,
        "in_reply_to_status_id"   => "",
        "in_reply_to_user_id"     => "",
        "in_reply_to_screen_name" => "",
        "thumbnail_pic"           => tencent_pic(tweet["image"], 160),
        "bmiddle_pic"             => tencent_pic(tweet["image"], 240),
        "original_pic"            => tencent_pic(tweet["image"], 460),
        "geo"                     => tweet["geo"],
        "mid"                     => tweet["id"],
        "reposts_count"           => nil,
        "comments_count"          => nil,
        "annotations"             => [],
        "user"                    => {
          "id"                      => tweet["openid"],
          "screen_name"             => tweet["nick"],
          "name"                    => tweet["name"],
          "province"                => tweet["province_code"],
          "city"                    => tweet["city_code"],
          "location"                => tweet["location"],
          "description"             => "",
          "url"                     => "http://t.qq.com/#{tweet["name"]}",
          "profile_image_url"       => tencent_pic(tweet["head"], "100"),
          "domain"                  => "",
          "gender"                  => "",
          "followers_count"         => nil,
          "friends_count"           => nil,
          "statuses_count"          => nil,
          "favourites_count"        => 0,
          "created_at"              => "",
          "following"               => false,
          "allow_all_act_msg"       => false,
          "remark"                  => "",
          "geo_enabled"             => true,
          "verified"                => false,
          "allow_all_comment"       => true,
          "avatar_large"            => "",
          "verified_reason"         => "",
          "follow_me"               => false,
          "online_status"           => 0,
          "bi_followers_count"      => nil
          }
        }
    end
    self.tweets = ts
  end

  def tencent_pic(pic, size = 100)
    if pic.present?
      if pic.is_a? Array
        pic[0] + "/#{size}"
      else
        "#{pic}/#{size}"
      end
    else
      nil
    end
  end

  def present_show
    present_add :tweets     => tweets,
                :task       => page_token.split('_')[0],
                :rendered   => false,
                :selected   => selected,
                :current_page => current_page,
                :page_token => page_token
  end
end